/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.fzhucc.modules.technical.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.pms.domain.Project;
import com.fzhucc.modules.pms.repository.ProjectRepository;
import com.fzhucc.modules.technical.domain.TechnicalProjectLog;
import com.fzhucc.modules.technical.domain.dto.TechnicalProjectDistributionDto;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.technical.repository.TechnicalProjectLogRepository;
import com.fzhucc.modules.technical.domain.dto.TechnicalProjectLogDto;
import com.fzhucc.modules.technical.domain.dto.TechnicalProjectLogQueryCriteria;
import com.fzhucc.modules.technical.service.mapstruct.TechnicalProjectLogMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author yyg
* @date 2022-12-16
**/
@Service
@RequiredArgsConstructor
public class TechnicalProjectLogService {

    private final TechnicalProjectLogRepository technicalProjectLogRepository;
    private final TechnicalProjectLogMapper technicalProjectLogMapper;

    private final ProjectRepository projectRepository;

    public Map<String,Object> queryAll(TechnicalProjectLogQueryCriteria criteria, Pageable pageable){
        Page<TechnicalProjectLog> page = technicalProjectLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(technicalProjectLogMapper::toDto));
    }

    public List<TechnicalProjectLogDto> queryAll(TechnicalProjectLogQueryCriteria criteria){
        return technicalProjectLogMapper.toDto(technicalProjectLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    public TechnicalProjectLogDto findById(Integer id) {
        TechnicalProjectLog technicalProjectLog = technicalProjectLogRepository.findById(id).orElseGet(TechnicalProjectLog::new);
        ValidationUtil.isNull(technicalProjectLog.getId(),"TechnicalProjectLog","id",id);
        return technicalProjectLogMapper.toDto(technicalProjectLog);
    }

    @Transactional(rollbackFor = Exception.class)
    public TechnicalProjectLogDto create(TechnicalProjectLog resources) {
        return technicalProjectLogMapper.toDto(technicalProjectLogRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(TechnicalProjectLog resources) {
        TechnicalProjectLog technicalProjectLog = technicalProjectLogRepository.findById(resources.getId()).orElseGet(TechnicalProjectLog::new);
        ValidationUtil.isNull( technicalProjectLog.getId(),"TechnicalProjectLog","id",resources.getId());
        technicalProjectLog.copy(resources);
        technicalProjectLogRepository.save(technicalProjectLog);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            technicalProjectLogRepository.deleteById(id);
        }
    }

    public void download(List<TechnicalProjectLogDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TechnicalProjectLogDto technicalProjectLog : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("分配时间", technicalProjectLog.getRelationTime());
            map.put("技术经理人id", technicalProjectLog.getTechnicalId());
            map.put("项目id", technicalProjectLog.getProjectId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Transactional
    public void dodistribution(TechnicalProjectDistributionDto technicalProjectDistributionDto) {
        String project_id = technicalProjectDistributionDto.getProjectId();
        List<Integer> list = technicalProjectDistributionDto.getListTechnicalId();
        Optional<Project> optionalProject = projectRepository.findById(project_id);
        if (optionalProject.isEmpty()) {
            throw new BadRequestException("项目未找到");
        }
        if (list == null) {
            throw new BadRequestException("技术经理人id list未找到");
        }
        //先删除所有该项目的绑定的技术经理人
        List<TechnicalProjectLog> listTechnicalProjectLog = technicalProjectLogRepository.findByProjectId(project_id);
        for (TechnicalProjectLog technicalProjectLog : listTechnicalProjectLog) {
            technicalProjectLogRepository.deleteById(technicalProjectLog.getId());
        }
        for (Integer ids : list) {
            //在新增新的技术经理人
            TechnicalProjectLog technicalProjectLog = new TechnicalProjectLog();
            technicalProjectLog.setProjectId(project_id);
            technicalProjectLog.setTechnicalId(ids);
            technicalProjectLog.setRelationTime(new Timestamp(new Date().getTime()));
            technicalProjectLogRepository.save(technicalProjectLog);
        }
    }

    public Map<String, Object> getTechnicalProjectByLoginUser(Pageable pageable) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("用户ID未找到");
        }
        Page<Project> page = projectRepository.findAllByTechnicalUser(userId, pageable);
        return PageUtil.toPage(page);
    }
}